<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
class GoodsClasslogic{

	/**
     * 分类列表
     * @param  int $user_id  操作用户ID
     * @author shiqiang
     * @return mixed
     */
    public function class_index($user_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' => $user_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			// $list = model('ErpGoodsClass', 'model') -> getClass();//获取列表
			// $rel_list = [];
            // foreach($list as $key => $value){
				// $goods_count = model('ErpGoods') -> where('goods_classid', $value['id']) -> count();
				
				// $rel_list[$key]['id'] 			= (int)$value['id'];
				// $rel_list[$key]['pid'] 			= (int)$value['pid'];
				// $rel_list[$key]['title'] 		= (string)$value['title'];
				// $rel_list[$key]['sort'] 			= (int)$value['sort'];
				// $rel_list[$key]['code'] 			= (string)$value['code'];
				// $rel_list[$key]['classImg']		= (string)$value['class_img'];
				// $rel_list[$key]['level']			= (string)$value['level'];
				// $rel_list[$key]['goodsCount']	= (int)$goods_count;
				// $rel_list[$key]['createTime'] 	= (int)$value['create_time'];
			// }
			
			$list = datacache('GoodsClass') -> getGoodClassLevel3();
			//第一步 构造数据
			$items = array();
			foreach($list as $value){
				$items[$value['id']] = $value;
			}
			//第二部 遍历数据 生成树状结构
			$tree = array();
			foreach($items as $key => $value){
				// $goods_count = model('ErpGoodsClassGl') -> where('class_id', $value['id']) -> count();
				
				$items[$key] = [];
				$items[$key]['id'] 			= (int)$value['id'];
				$items[$key]['pid'] 		= (int)$value['pid'];
				$items[$key]['title'] 		= (string)$value['title'];
				$items[$key]['sort'] 		= (int)$value['sort'];
				$items[$key]['code'] 		= (string)$value['code'];
				$items[$key]['classImg']	= (string)$value['class_img'];
				$items[$key]['level']		= (int)$value['level'];
				// $items[$key]['goodsCount']	= (int)$goods_count;
				$items[$key]['createTime'] 	= (int)$value['create_time'];
				// if($value['level'] < 3) $items[$key]['childs'] = [];
				
				if(isset($items[$value['pid']])){
					$items[$value['pid']]['childs'][] = &$items[$key];
				}else{
					$tree[] = &$items[$key];
				}
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $tree);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 添加
     * @param  int    $user_id   操作用户ID
     * @param  int    $pid  	 父级id（顶级 = 0）
     * @param  string $title  	 分类标题
     * @param  int    $sort  	 分类排序
     * @param  string $code  	 分类编码
     * @param  string $class_img 分类图片
     * @author shiqiang
     * @return mixed
     */
    public function add($user_id, $pid, $title, $sort, $code, $class_img){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'pid' 		=> $pid,
				'title' 	=> $title,
				'sort' 		=> $sort,
				'code' 		=> $code,
				'class_img' => $class_img,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$father_path = '';
			if($pid > 0){
				$father_path = model('ErpGoodsClass') -> find($pid) -> path;//上级path
				$level = explode('-', $father_path);
				if(count($level) > 2){
					DB::rollback();
					return array_out(-1005, 'error3');//类目不能超过3级
				}
			}
			
			$rel = model('ErpGoodsClass') -> addData($pid, $title, $sort, $code, $class_img);//添加
			if($rel['code'] == 200){
				$class_id 	= $rel['data'];
				$path 		= $class_id;
				if($father_path != ''){
					$path = $father_path . '-' .$path;//重组path
				}
				$rel = model('ErpGoodsClass') -> updateDataByPath($class_id, $path);
				if($rel['code'] < 0){
					DB::rollback();
					return array_out(-1005, 'error2');//path更新失败 返回-1005,error
				}
			}else{
				DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
			}

            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
			datacache('GoodsClass') -> getGoodClassLevel3(true);
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 编辑
     * @param  int    $user_id   操作用户ID
     * @param  int    $id  		分类id
     * @param  int    $pid  	 父级id（顶级 = 0）
     * @param  string $title  	 分类标题
     * @param  int    $sort  	 分类排序
     * @param  string $code  	 分类编码
     * @param  string $class_img 分类图片
     * @author shiqiang
     * @return mixed
     */
    public function edit($user_id, $id, $pid, $title, $sort, $code, $class_img){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
				'pid' 		=> $pid,
				'title' 	=> $title,
				'sort' 		=> $sort,
				'code' 		=> $code,
				'class_img' => $class_img,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$father_path = '';
			$new_path = $id;
			if($pid > 0){
				$father_path = model('ErpGoodsClass') -> find($pid) -> path;//上级path
				$level = explode('-', $father_path);
				if(count($level) > 2){
					DB::rollback();
					return array_out(-1005, 'error3');//类目不能超过3级
				}
				$new_path = $father_path . '-' .$new_path;//重组path
			}
			
			
			$rel = model('ErpGoodsClass') -> editData($id ,$pid, $title, $sort, $code, $class_img);
			if($rel['code'] == 200){
				// $path = model('ErpGoodsClass') -> find($id) -> path;
				// $childs_path = model('ErpGoodsClass') -> getChildsPath($id);//所有子集path
				// $childs_path[$id] = $new_path; //本条数据 插入数据集
				// foreach($childs_path as $key => $value){
					// $path	= str_replace($path, $new_path, $value);
					// $rel = model('ErpGoodsClass') -> updateDataByPath($key, $path);
					// if($rel['code'] < 0){
						// DB::rollback();
						// return array_out(-1005, 'error2');//path更新失败 返回-1005,error
					// }
				// }
			}else{
				DB::rollback();
                return array_out(-1005, 'error');//编辑失败 返回-1005,error
			}

            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
			datacache('GoodsClass') -> getGoodClassLevel3(true);
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 删除
     * @param  int    $user_id   操作用户ID
     * @param  int    $id  		分类id
     * @author shiqiang
     * @return mixed
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$class_childs = model('ErpGoodsClass') -> getChildsId($id); // 获取所有子类id
			$all_class_id = array_merge([(int)$id], $class_childs);// 要删除的所有id
			foreach($all_class_id as $class_id){
				$rel = model('ErpGoodsClassGl') -> where('class_id', $class_id) -> find();
				if(!empty($rel)){
					return array_out(-1005, 'error1');//删除失败 分类下有商品，无法删除 返回-1005,error
				}
			}
			$rel = model('ErpGoodsClass') -> deleteData($all_class_id);
			if($rel['code'] < 0){
				return array_out(-1005, 'error');//删除失败 返回-1005,error
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
			datacache('GoodsClass') -> getGoodClassLevel3(true);
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}